﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using blackhouse.BlackApart.Data;
using blackhouse.Locations;
using System.Globalization;

namespace blackhouse.BlackApart.Business.Places {
	public class DaPlace : IPlace {

		#region Fields

		private IPlaceDataAccess data;
		private ImpPlace instance;

		#endregion

		#region Properties


		public int PlaceId {
			get {
				return this.instance.PlaceId;
			}

			private set {
				if (this.instance.PlaceId == 0) {
					this.instance.PlaceId = value;
				}
				else {
					if (this.instance.PlaceId != value)
						throw new NotSupportedException("Nie można zmienić id już istniejącego obiektu");
				}
			}

		}

		public string Name {
			get {
				return this.instance.Name;
			}
			set {
				this.instance.Name = value;
			}
		}

		public Location Location {
			get {
				return this.instance.Location;
			}
			set {
				this.instance.Location = value;
			}
		}

		public string Address {
			get {
				return this.instance.Address;
			}
			set {
				this.instance.Address = value;
			}
		}

		public string Description {
			get {
				return this.instance.Description;
			}
			set {
				this.instance.Description = value;
			}
		}

		public string Category {
			get {
				return this.instance.Category;
			}
			set {
				this.instance.Category = value;
			}
		}


		#endregion

		#region Constructors

		public DaPlace(IPlaceDataAccess dataAccess) {
			this.data = dataAccess;
			this.instance = new ImpPlace();
		}

		private DaPlace(IPlaceDataAccess dataAccess, PlaceData data) {
			this.data = dataAccess;
			this.instance = this.Convert(data);
		}

		#endregion

		#region Methods

		public IPlace[] GetAllPlaces() {
			DaPlace[] places = this.data.GetAllPlaces(CultureInfo.CurrentCulture.Name).Select(p => new DaPlace(this.data, p)).ToArray();
			foreach (DaPlace place in places)
				place.SetAllPlaces(places);
			return places;
		}

		private ImpPlace Convert(PlaceData data) {
			ImpPlace place = new ImpPlace();
			place.Address = data.Address;
			place.Category = data.Category;
			place.Description = data.Description;
			place.Location = new Location() { Latitude = data.LocationLatitude, Longitude = data.LocationLongitude };
			place.Name = data.Name;
			place.PlaceId = data.PlaceId;
			return place;
		}

		private void SetAllPlaces(IPlace[] places) {
			this.instance.AllPlaces = places;
		}

		#endregion

	}
}
